package org.meeting.radish.controller;

import lombok.extern.slf4j.Slf4j;
import org.meeting.radish.entity.Question;
import org.meeting.radish.entity.TestCase;
import org.meeting.radish.entity.UserAnswer;
import org.meeting.radish.oj.CodeTypeException;
import org.meeting.radish.oj.OjParameter;
import org.meeting.radish.service.QuestionService;
import org.meeting.radish.service.TestCaseService;
import org.meeting.radish.service.UserAnswerService;
import org.meeting.radish.util.OjUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Controller
@RequestMapping("/question")
public class UserAnswerController {

    @Resource
    QuestionService questionService;

    @Resource
    UserAnswerService userAnswerService;

    @Resource
    TestCaseService testCaseService;

    @GetMapping("/{qid}")
    public String getQuestionMsg(@PathVariable("qid") Integer qid, Map<String, Object> map) {
        Question question = questionService.queryQuestionByQid(qid);
        log.info("qid为{}的题目{}", qid, question);
        map.put("question", question);
        Set<String> codeTypes = OjParameter.OjProperties.codeTypeAndRun.keySet();
        map.put("codeTypes", codeTypes);
        return "compose";
    }

    private byte falseVule = 0;
    private byte halfTrueValue = 1;
    private byte trueVule = 2;

    @PostMapping("/judge")
    public String userAnswer(UserAnswer userAnswer, String codeType, String code) throws CodeTypeException, IOException, InterruptedException {
        log.info("{}|{}|{}", userAnswer, codeType, code);
        OjUtil ojUtil = OjUtil.getOjUtil(userAnswer, codeType, code);
        Map<Boolean, String> compile = ojUtil.compile();
        if (compile.containsKey(false)) {
            userAnswer.setStatus(falseVule);
        }

        List<TestCase> testCases = testCaseService.queryTestCaseByQid(userAnswer.getQid());
        Map<Boolean, String> result = ojUtil.run(testCases);

        if (!result.containsKey(true) && result.containsKey(false)) {
            // 完全错误
            userAnswer.setStatus(falseVule);
        } else if (result.containsKey(true) && !result.containsKey(false)) {
            // 完全正确
            userAnswer.setStatus(trueVule);
        } else if (result.containsKey(true) && result.containsKey(false)) {
            // 部分正确
            userAnswer.setStatus(halfTrueValue);
        }

        userAnswerService.submitUserAnswer(userAnswer);

        return "redirect:/questions/all";
    }
}
